<template>
  <div class="upload-example-container">
    <div class="page-header">
      <h2>上传组件示例</h2>
      <p>本页面展示了不同类型的文件上传组件及使用方法</p>
    </div>

    <!-- 基础上传 -->
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <h3>基础上传</h3>
          <el-tag type="primary">单文件</el-tag>
        </div>
      </template>

      <el-upload
        class="upload-demo"
        action="/api/upload/file"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :on-exceed="handleExceed"
        :file-list="fileList"
      >
        <el-button type="primary">点击上传</el-button>
        <template #tip>
          <div class="el-upload__tip">
            支持 jpg/png 文件，且不超过 500kb
          </div>
        </template>
      </el-upload>
    </el-card>

    <!-- 拖拽上传 -->
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <h3>拖拽上传</h3>
          <el-tag type="success">多文件</el-tag>
        </div>
      </template>

      <el-upload
        class="upload-drag"
        drag
        action="/api/upload/files"
        multiple
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :on-exceed="handleExceed"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持多个文件同时上传，每个文件不超过 10MB
          </div>
        </template>
      </el-upload>
    </el-card>

    <!-- 头像上传 -->
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <h3>头像上传</h3>
          <el-tag type="warning">图片剪裁</el-tag>
        </div>
      </template>

      <el-upload
        class="avatar-uploader"
        action="/api/upload/avatar"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>
      </el-upload>
      <div class="avatar-tip">
        点击上方区域上传头像，只支持 JPG/PNG 格式，大小不超过 2MB
      </div>
    </el-card>

    <!-- 图片墙 -->
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <h3>图片墙</h3>
          <el-tag type="danger">相册展示</el-tag>
        </div>
      </template>

      <el-upload
        action="/api/upload/images"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="beforeImageWallUpload"
      >
        <el-icon><plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible" title="预览图片">
        <img w-full :src="dialogImageUrl" alt="预览图片" />
      </el-dialog>
    </el-card>

    <!-- 自定义上传 -->
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <h3>自定义上传</h3>
          <el-tag type="info">手动控制</el-tag>
        </div>
      </template>

      <div class="custom-upload">
        <el-input v-model="customUploadName" placeholder="请输入文件名称" class="name-input" />
        <el-select v-model="customUploadType" placeholder="选择文件类型" class="type-select">
          <el-option label="文档" value="doc" />
          <el-option label="图片" value="image" />
          <el-option label="视频" value="video" />
          <el-option label="其他" value="other" />
        </el-select>
        <el-upload
          class="custom-upload-btn"
          action="/api/upload/custom"
          :auto-upload="false"
          :on-change="handleCustomChange"
          :file-list="customFileList"
          ref="customUploadRef"
        >
          <template #trigger>
            <el-button type="primary">选择文件</el-button>
          </template>
          <el-button type="success" @click="submitCustomUpload" :disabled="!customFileList.length">
            上传到服务器
          </el-button>
          <template #tip>
            <div class="el-upload__tip">
              支持所有类型文件，自定义上传信息
            </div>
          </template>
        </el-upload>
      </div>
    </el-card>

    <!-- 文件上传限制 -->
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <h3>文件上传限制</h3>
          <el-tag>格式验证</el-tag>
        </div>
      </template>

      <div class="limit-upload">
        <div class="limit-options">
          <div class="limit-option">
            <span class="limit-label">文件大小限制：</span>
            <el-input-number v-model="sizeLimit" :min="1" :max="20" :step="1" />
            <span>MB</span>
          </div>
          <div class="limit-option">
            <span class="limit-label">允许的格式：</span>
            <el-select v-model="formatLimit" multiple placeholder="选择允许的文件格式">
              <el-option label="JPG" value=".jpg" />
              <el-option label="PNG" value=".png" />
              <el-option label="PDF" value=".pdf" />
              <el-option label="DOC" value=".doc" />
              <el-option label="DOCX" value=".docx" />
              <el-option label="XLS" value=".xls" />
              <el-option label="XLSX" value=".xlsx" />
              <el-option label="ZIP" value=".zip" />
            </el-select>
          </div>
        </div>

        <el-divider />

        <el-upload
          class="limit-upload-demo"
          action="/api/upload/validation"
          :before-upload="validateFile"
          :on-success="handleLimitSuccess"
          :on-error="handleLimitError"
        >
          <el-button type="primary">上传文件（带验证）</el-button>
          <template #tip>
            <div class="el-upload__tip">
              请先在上方设置文件限制条件，然后上传文件
            </div>
          </template>
        </el-upload>

        <div class="validation-result" v-if="validationMessage">
          <el-alert
            :title="validationMessage"
            :type="validationSuccess ? 'success' : 'error'"
            show-icon
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled, Plus } from '@element-plus/icons-vue'

// 基础上传
const fileList = ref([])

const handleRemove = (file, fileList) => {
  console.log(file, fileList)
  ElMessage.info(`已移除文件: ${file.name}`)
}

const handlePreview = (file) => {
  console.log(file)
  window.open(file.url)
}

const handleExceed = (files, fileList) => {
  ElMessage.warning(`超出上传限制，当前限制为 ${files.length} 个文件，您选择了 ${files.length + fileList.length} 个文件`)
}

const beforeRemove = (file) => {
  return ElMessageBox.confirm(`确定移除 ${file.name}？`)
}

// 头像上传
const imageUrl = ref('')

const handleAvatarSuccess = (response, file) => {
  // 实际应用中使用response中的图片URL
  imageUrl.value = URL.createObjectURL(file.raw)
  ElMessage.success('头像上传成功')
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }

  return isJPG && isLt2M
}

// 图片墙
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const beforeImageWallUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
  }

  return isImage && isLt5M
}

// 自定义上传
const customUploadRef = ref(null)
const customUploadName = ref('')
const customUploadType = ref('')
const customFileList = ref([])

const handleCustomChange = (file, fileList) => {
  customFileList.value = fileList
}

const submitCustomUpload = () => {
  if (!customUploadName.value) {
    ElMessage.warning('请输入文件名称')
    return
  }
  if (!customUploadType.value) {
    ElMessage.warning('请选择文件类型')
    return
  }
  
  // 在实际应用中，可以将自定义信息添加到请求中
  console.log('自定义上传信息:', {
    name: customUploadName.value,
    type: customUploadType.value,
    files: customFileList.value
  })
  
  customUploadRef.value.submit()
  ElMessage.success('文件已提交上传，请查看控制台信息')
}

// 文件上传限制
const sizeLimit = ref(5)
const formatLimit = ref(['.jpg', '.png', '.pdf'])
const validationMessage = ref('')
const validationSuccess = ref(false)

const validateFile = (file) => {
  // 检查文件大小
  const isLtLimit = file.size / 1024 / 1024 < sizeLimit.value
  if (!isLtLimit) {
    validationMessage.value = `文件大小超过了限制 (${sizeLimit.value}MB)`
    validationSuccess.value = false
    ElMessage.error(validationMessage.value)
    return false
  }

  // 检查文件格式
  if (formatLimit.value.length > 0) {
    const fileName = file.name.toLowerCase()
    const extension = fileName.substring(fileName.lastIndexOf('.'))
    const isValidFormat = formatLimit.value.some(format => format.toLowerCase() === extension)
    if (!isValidFormat) {
      validationMessage.value = `不支持的文件格式 (${extension})`
      validationSuccess.value = false
      ElMessage.error(validationMessage.value)
      return false
    }
  }

  validationMessage.value = `文件 ${file.name} 验证通过`
  validationSuccess.value = true
  return true
}

const handleLimitSuccess = (response, file) => {
  validationMessage.value = `文件 ${file.name} 上传成功`
  validationSuccess.value = true
  ElMessage.success(validationMessage.value)
}

const handleLimitError = (error, file) => {
  validationMessage.value = `文件 ${file.name} 上传失败：${error.message || '未知错误'}`
  validationSuccess.value = false
  ElMessage.error(validationMessage.value)
}
</script>

<style scoped>
.upload-example-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  margin-bottom: 10px;
}

.page-header p {
  color: #666;
  font-size: 14px;
}

.upload-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
}

.upload-drag {
  width: 100%;
}

.upload-drag .el-upload {
  width: 100%;
}

/* 头像上传样式 */
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: inline-block;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.avatar-tip {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

/* 自定义上传样式 */
.custom-upload {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.name-input {
  width: 100%;
}

.type-select {
  width: 100%;
}

.custom-upload-btn {
  margin-top: 10px;
}

/* 文件限制上传样式 */
.limit-options {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 15px;
}

.limit-option {
  display: flex;
  align-items: center;
  gap: 10px;
}

.limit-label {
  color: #606266;
  width: 120px;
}

.validation-result {
  margin-top: 15px;
}
</style> 